#pragma once
#include "Log.hpp"
#include <sstream>
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>

class Util
{
    public:
    //使用输入输出型参数，等到读取结果
    static ssize_t Readline(int sock,std::string& out)
    {
        char ch='x';
        while(ch != '\n')
        {

            //ssize_t recv(int sockfd, void *buf, size_t len, int flags);
            ssize_t n=recv(sock,&ch,1,0);
            if(n>0)
            {
                //因为不同的平台的实现的Http协议的结尾符号可能不同，所以要考虑不同平台的兼容性
                //“/n” “/r/n” “/r”
                if(ch == '\r')
                {
                    //窥探读，不改变接受缓冲区内容
                    recv(sock,&ch,1,MSG_PEEK);
                    if(ch == '\n')
                    {
                        //把\r\n->\n
                        recv(sock,&ch,1,0);
                    }
                    else
                    {
                        //把\r->\n
                        ch = '\n';
                    }
                }
                //这里的是普通字符或者是'\r'
                out+=ch;
            }
            else if(n == 0)
            {
               break;
            }
            else 
            {
                LOG(ERROR,"recv failed");
                return -1;
            }
        }
        return out.size(); 
    }

    static bool Cutstring(std::string str,std::string& s1,std::string& s2,std::string sep)
    {
        size_t pos=str.find(sep);
        if(pos == std::string::npos)
        {
            LOG(FATAL,"find sep failed");
        }
       else
       {
        s1=str.substr(0,pos);
        s2=str.substr(sep.size()+pos);
        return true;
       }
       
    }

    static string Code_To_Desc(int code)
    {
        if(code == 200)
        {
            return "OK";
        }
        else if(code == 404)
        {
            return "NOT FONUND";
        }
        else
        {
            return "NO KONWING";
        }
        return "ERROR";
    }
};